package org.kamimark.java.util;

import java.util.Hashtable;

public class TextTools
{

	private static final String FROM_ARG_REG_EX = "\\{(\\d)\\}";
	private static final String TO_ARG_REG_EX = "%$1\\$s";

	private static Hashtable<Object, StringBuilder> streams = new Hashtable<Object, StringBuilder>();

	/**
	 * @param base -
	 *            The main string where the other strings will attach to.
	 * @param strings -
	 *            <p>
	 *            Example:</br> base = "{2} two {1} four.";<br/> strings = new String []
	 *            {"three","one"};<br/> Results in: "one two three four."
	 *            </p>
	 */
	public static String merge(CharSequence base, Object... strings) {
		String formatterStr = base.toString().replaceAll(FROM_ARG_REG_EX, TO_ARG_REG_EX);
		return String.format(formatterStr, strings);
	}

	public static String merge(String base, Object... strings) {
		String formatterStr = base.replaceAll(FROM_ARG_REG_EX, TO_ARG_REG_EX);
		return String.format(formatterStr, strings);
	}

	/**
	 * @param obj
	 * @return gives a String with all the data in the text stream represented by obj
	 */
	public static String dumpStream(Object obj) {

		StringBuilder builder = streams.get(obj);
		if (builder == null)
			throw new RuntimeException("Cannot dump a stream that was never stacked.");

		String body = builder.toString();
		builder.delete(0, builder.length() - 1);

		return body;
	}

	/**
	 * Stacks a CharSequence in the text stream represented by obj
	 * 
	 * @param obj
	 * @param str
	 *            the CharSequence to stack
	 */
	public static void stack(Object obj, CharSequence str) {
		StringBuilder builder = streams.get(obj);
		if (builder == null) {
			builder = new StringBuilder();
			streams.put(obj, builder);
		}
		builder.append(str);
	}

}
